"""
Created on Jul 12, 2010

@author: adolfo

Module that contains the application context configuration for the automated
tests performed on the SMS gateway modules for the SMSAppStore project.
"""
from springpython.database.factory import Sqlite3ConnectionFactory
from springpython.config import PythonConfig, Object
from ..kannel_sms_gateway import KannelSMSGateway
from ..gammu_sms_gateway import GammuSMSGateway
from ..sms_gateway import Message
import logging.handlers

_LOGGER = logging.getLogger(
        "mx.org.came.tests.sms_gateway_test_application_context")

class SMSGatewayTestConfig(PythonConfig):
    """ Base application context configuration for the implementations of SMSGateway
    in the SMSAppStore project.
    For more information, visit `Spring Python's home page
    <http://springpython.webfactional.com/>`_.
    """

    def __init__(self):
        PythonConfig.__init__(self)

    @Object
    def root_logger(self):
        """Configures the loggers to be used during testing and returns
        the root logger. This object is never explicitly used,
        since Spring Python eagerly creates it, and by doing so, the logging
        is configured"""

        LOG_FILENAME = "../target/test/sms_gateway_tests.log"
        LOG_FORMAT = "%(asctime)s - [%(name)s] - [%(levelname)s] - %(message)s"

        #File logging configuration
        file_handler = logging.handlers.RotatingFileHandler(
                LOG_FILENAME,
                maxBytes=2000000,
                backupCount=5)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
        logging.getLogger().addHandler(file_handler)

        #Console logging configuration
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(logging.Formatter(LOG_FORMAT))
        logging.getLogger().addHandler(console_handler)

        #Logging levels for the different application packages
        logging.getLogger().setLevel(logging.INFO)
        logging.getLogger("mx.org.came").setLevel(logging.DEBUG)

        return logging.getLogger()

class KannelSMSGatewayTestConfig(SMSGatewayTestConfig):
    """Application context configuration for the implementation of SMSGateway
    for Kannel.
    For more information, visit `Spring Python's home page
    <http://springpython.webfactional.com/>`_.
    """

    @Object
    def default_kannel_sms_gateway(self):
        """Returns an instance of KannelSMSGateway with the default
        configuration"""
        return KannelSMSGateway()

    @Object
    def kannel_sms_gateway(self):
        """Configures the instance of KannelSMSGateway used in the tests."""
        gateway = KannelSMSGateway(notification_server_address = "127.0.0.1"
                                   , notification_server_port = 55055
                                   , kannel_server_address = "kannel.example.org"
                                   , kannel_server_port = 13131
                                   , kannel_user = "user"
                                   , kannel_password = "password"
                                   , kannel_phone_number = 2381280891
                                   , kannel_url_parameters = "%p&%u&%b")
        return gateway
        

class GammuSMSGatewayTestConfig(SMSGatewayTestConfig):
    """Application context configuration for the implementation of SMSGateway
    for Gammu.
    For more information, visit `Spring Python's home page
    <http://springpython.webfactional.com/>`_.
    """

    GAMMU_MESSAGE_RETRIEVAL_QUERY_SQL = """
            SELECT SenderNumber, UDH, Text, TextDecoded
            FROM inbox
            WHERE ID = %s
            """
    
    GAMMU_MESSAGE_DELIVERY_QUERY_SQL ="""
            INSERT INTO outbox (DestinationNumber, UDH, Text, TextDecoded, Coding
            , ID, UpdatedInDB, InsertIntoDB, SendingDateTime 
            , Class,  MultiPart, RelativeValidity, SenderID
            , SendingTimeOut, DeliveryReport, CreatorID)
            VALUES (%s, %s, %s, %s, %s
            , NULL, CURRENT_TIMESTAMP, '0000-00-00 00:00:00', '0000-00-00 00:00:00'
            , '-1', 'false', '-1', NULL
            , '0000-00-00 00:00:00', 'default', ''
            )"""

    @Object
    def gammu_connection_factory(self):
        """Configures the database connection factory to be used to query
        Gammu's database.
        """
        connection_factory = Sqlite3ConnectionFactory("../target/test/gateway_test.db")
        return connection_factory

    @Object
    def gammu_sms_gateway(self):
        gateway = GammuSMSGateway(gammu_db_connection_factory = self.gammu_connection_factory()
                                  , notification_server_address = "127.0.0.1"
                                  , notification_server_port = 22222
                                  , gammu_phone_number = 2381280891
                                  , gammu_message_retrieval_query = GammuSMSGatewayTestConfig.GAMMU_MESSAGE_RETRIEVAL_QUERY_SQL
                                  , gammu_message_delivery_query = GammuSMSGatewayTestConfig.GAMMU_MESSAGE_DELIVERY_QUERY_SQL)
        return gateway

    @Object
    def text_message(self):
        message = Message()
        message.data[Message.UDH] = ""
        message.data[Message.ORIGINAL_BINARY_MESSAGE] = "A simple text message."
        message.data[Message.SENDER_PHONE_NUMBER] = "2381280921"
        message.data[Message.RECEIVER_PHONE_NUMBER] = None
        return message
    
    @Object
    def binary_message(self):
        message = Message()
        message.data[Message.UDH] = "\x06\x05\x04\xDF\x8B\x00\x00"
        message.data[Message.ORIGINAL_BINARY_MESSAGE] = "\x01\x06\x01\x00\x07\x01\x04\x00\x00\x63\xa8"
        message.data[Message.SENDER_PHONE_NUMBER] = "2381280921"
        message.data[Message.RECEIVER_PHONE_NUMBER] = None
        return message
    